package com.alex.utils.image;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;

public class ImageUtils {

	public static BufferedImage scaleImage(BufferedImage image, int width, int height) {
		BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics = scaledImage.createGraphics();

		if (!graphics.drawImage(image.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null))
			scaledImage.flush();

		return scaledImage;
	}
	
	public static BufferedImage createImageThumb(BufferedImage image, int width, int height) {
		BufferedImage scaledImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics = scaledImage.createGraphics();

		float aspect = width / height;
		if ((float) image.getWidth() / image.getHeight() > aspect) {
			int newWidth = width;
			int newHeigth = image.getHeight() * width / image.getWidth();
			
			int x = 0;
			int y = (height - newHeigth) / 2;
			
			if (!graphics.drawImage(image, x, y, newWidth, y + newHeigth, 0, 0, image.getWidth(), image.getHeight(), Color.WHITE, null)) {
				scaledImage.flush();
			}
			
		} else {
			int newWidth = image.getWidth() * height / image.getHeight();
			int newHeigth = height;
			
			int x = (width - newWidth) / 2;
			int y = 0;
			
			if (!graphics.drawImage(image, x, y, x + newWidth, newHeigth, 0, 0, image.getWidth(), image.getHeight(), Color.WHITE, null)) {
				scaledImage.flush();
			}
		}
		
		return scaledImage;
	}
	
	public static BufferedImage fitImage(BufferedImage image, int width, int height) {
		BufferedImage scaledImage = null;
		
		float aspect = width / height;
		if ((float) image.getWidth() / image.getHeight() > aspect) {
			int newWidth = width;
			int newHeigth = image.getHeight() * width / image.getWidth();
			
			scaledImage = new BufferedImage(newWidth, newHeigth, BufferedImage.TYPE_INT_RGB);
			Graphics2D graphics = scaledImage.createGraphics();
			
			if (!graphics.drawImage(image, 0, 0, newWidth, newHeigth, 0, 0, image.getWidth(), image.getHeight(), Color.WHITE, null)) {
				scaledImage.flush();
			}
			
		} else {
			int newWidth = image.getWidth() * height / image.getHeight();
			int newHeigth = height;
			
			scaledImage = new BufferedImage(newWidth, newHeigth, BufferedImage.TYPE_INT_RGB);
			Graphics2D graphics = scaledImage.createGraphics();
			
			if (!graphics.drawImage(image, 0, 0, newWidth, newHeigth, 0, 0, image.getWidth(), image.getHeight(), Color.WHITE, null)) {
				scaledImage.flush();
			}
		}
		
		return scaledImage;
	}
}
